import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 30000 // 请求超时时间
})

// 异常处理
const errorHandler = (error) => {
  // 从 localstorage 获取 token
  const token = storage.get(ACCESS_TOKEN)
  console.info(token,'token1 errorHandler')
  console.info(error,'error2 errorHandler')
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json'
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['n8-admin-token'] = token
  }
  return config
}, errorHandler)


let num = 1
// response interceptor
request.interceptors.response.use( 
  response => {
    const res = response.data
    const token = storage.get(ACCESS_TOKEN)
    if (res.code !== 'SUCCESS') {
      if ( num === 0) return
      num = 0
      if ( res.code === 'UNLOGIN') {
        const key = `open${Date.now()}`;
        notification.open({
          message: '登录过期',
          description: '登录过期，请重新登录',
          style:'color: red',
          key,
          onClose: close,
          btn: h => {
            return h(
              'a-button',
              {
                props: { type: 'primary', size: 'small' },
                on: {
                  click: () => {
                    if (token) store.dispatch('Logout').then(() => { setTimeout( () => { window.location.reload() }, 1500) })
                  }
                },
              },
              '重新登录',
            )
          }
        });
      }else {
        notification.error({
          message: 'Forbidden',
          description: res.message
        })
      }
      setTimeout(() => {
        num = 1
      }, 5000);
    }
    return res
  }, 
  errorHandler
)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
